<template>
	<!-- 选集弹窗 -->
	<view>
		<view class="content-nav">
			<u-popup :show="showGroup" :round="10" mode="bottom" :z-index="10076" @close="handleClose()">
				<view class="title-nav">
					<view class="font-36 font-color font-bold">{{ libraryData.title }}</view>
					<template v-if="isEnd">
						<view class="font-28 font-color-2 ml-20">已完结{{ libraryData.total_plot_num }}集全</view>
					</template>
					<template v-else>
						<view class="font-28 font-color-2 ml-20">更新至第{{ libraryData.update_plot_num }}集</view>
					</template>
				</view>

				<u-tabs :list="groupTabList" :scrollable="true" :current="activeIndex" :lineColor="mainColor"
					:inactiveStyle="{color: fontColor2}" :activeStyle="{ fontWeight: 'bold', color: mainColor }"
					@click="groupTabClick" />

				<scroll-view scroll-y="true" style="height: 50vh;">
					<view class="video-nave">
						<view v-for="(item,index) in videoList" :key="item.episode_id" class="video-item"
							@click="videiItemClick(item)">
							<u-image :src="libraryData.oss_object.url" width="100%" height="300rpx" radius="20rpx">
							</u-image>
							<template v-if="playerEpisodeNumber == item.episode">
								<view class="plaery-ing">刚刚播放</view>
							</template>
							<view class="episode-text">第 {{ item.episode }} 集</view>
							<template v-if="item.episode_price > 0 && item.is_buy === 0">
								<view class="lock-nav">
									<view class="lock-icon">
										<u-image src="/static/images/lock.png" width="64rpx" height="64rpx">
										</u-image>
									</view>
								</view>
							</template>
						</view>
					</view>
					<u-gap height="30rpx" />
				</scroll-view>
			</u-popup>
		</view>

	</view>
</template>

<script>
import colorMixins from '@/mixins/colorMixins.js'
import { queryBalance } from '@/api/user.js'
import { headerParams } from '@/config/headerParams.js'
import storage from '@/utils/storage.js'
import { CHANNEL_ID } from '@/store/mutation-types.js'

export default {
  name: 'PlayerGroup',
  mixins: [colorMixins],
  props: {
    libraryData: {
      type: Object,
      default: () => {}
    },
    showGroup: {
      type: Boolean,
      default: false,
    },
    // 所有剧集数据源
    allList: {
      type: Array,
      default: () => []
    },
    // 正在播放的剧集数
    playerEpisodeNumber: {
      type: Number,
      default: 0,
    }
  },
  data() {
    return {
      activeIndex: 0,
      total: 0, // 总集数，取所有剧集的长度
      groupTabList: [],
      videoList: [],
    }
  },
  computed: {
    // true 已完结
    isEnd() {
      return this.$props.libraryData.is_end == 1
    },
    isIOS() {
      return this.$store.state.systemInfo.osName == 'ios'
    },
    canPayIOS() {
      return this.$store.state.appConfig.is_ireg == 1
    },
    isDefaultChannel() {
      const nowChannelId = storage.get(CHANNEL_ID)
      const defaultChannelId = headerParams.pid
      return nowChannelId == defaultChannelId
    },
    // ios系统根据条件判断能否支付, true允许
    shouldPayIOS() {
		  let result = false
		  if (this.isIOS) {
			  if (this.canPayIOS && !this.isDefaultChannel) {
			    result = true
			  }
		  } else {
			  result = true
		  }
		  return result
    }
  },
  watch: {
    showGroup: {
      handler(val) {
        if (val) this.queryBalanceFn()
      }
    },
    allList: {
      handler(val) {
        console.log('player-group组件watch==', val)
        if (val.length == 0) return false

        this.total = val.length
        this.computeGroup().then(() => {
          this.getVideoList()
        })
      },
      deep: true
    },
  },
  created() {

  },
  methods: {
    handleClose() {
      this.$emit('update:showGroup', false)
    },

    // 查用户余额
    async queryBalanceFn() {
      const data = await queryBalance()
      this.balance = Math.ceil(data.coin)
    },

    // tab切换
    groupTabClick(item) {
      console.log('tab分组切换', item)
      const {
        index,
        start,
        end
      } = item
      this.activeIndex = index
      this.getVideoList()
    },

    // 计算一共有多少组数据
    async computeGroup() {
      this.groupTabList = []

      if (this.total < 31) {
        // if (this.total < 4) {
        // 当总集数不超过30集，直接1到总集数
        this.groupTabList.push({
          name: '1-' + this.total,
          start: 1,
          end: this.total
        })
      } else {
        const b = this.total / 30
        // const b = this.total / 4
        const intb = Math.ceil(b)
        // console.log("最后一部分的集数=", intb); //向上取整数
        for (var i = 0; i < intb; i++) {
          let start = i * 30 + 1
          let end = i * 30 + 30
          // let start = i * 4 + 1
          // let end = i * 4 + 4
          if (end > this.total) {
            end = this.total
          }
          this.groupTabList.push({
            name: start + '-' + end,
            start: start,
            end: end
          })
        }
      }
    },

    // 获取剧集数据
    getVideoList() {
      const tabItem = this.groupTabList[this.activeIndex]
      // 选中分组tab的开始剧集下标，结束剧集下标
      const {
        start,
        end
      } = tabItem
      const arr = this.$props.allList.filter((item, index) => {
        const transIndex = index + 1
        if (transIndex >= start && transIndex <= end) {
          return item
        }
      })
      this.videoList = arr
    },

    // 点击某一集播放
    videiItemClick(item) {
      const {
        episode_id,
        episode_price,
        is_buy
      } = item
      const episodePrice = Number(episode_price)
      const findIndex = this.$props.allList.findIndex(e => e.episode_id == episode_id)
			
      if(episodePrice > 0 && is_buy === 0 && this.shouldPayIOS === false) {
			  return uni.$u.toast('IOS端暂不支持该功能')
      }
			
      if (episodePrice > 0) {
        // 剧集价格大于0，才需要购买
        if (this.balance < episodePrice && is_buy === 0) {
          // 拉起支付弹框
          this.$emit('update:showGroup', false)
          this.$emit('needRecharge', true)
          this.$emit('resultIndex', findIndex)
        } else if (episodePrice > 0 && is_buy === 0) {
          // 拉起余额支付弹框
          this.$emit('balanceSubmit', findIndex)
        } else {
          // 直接播放
          this.$emit('update:showGroup', false)
          this.$emit('resultIndex', findIndex)
        }
      } else {
        // 直接播放
        this.$emit('update:showGroup', false)
        this.$emit('resultIndex', findIndex)
      }
    },

    // 购买分集-确认
    balanceModalSubmitHandle() {
      // const {
      //   itemData,
      //   index
      // } = this.balanceModal

      // vk.pubfn.debounce(() => {
      //   this.balanceModal.show = false
      //   this.paySeries(itemData, index)
      // }, 1000)
    },
    // 购买分集-取消
    balanceModalCancelHandle() {
      this.balanceModal.show = false
      // 点取消，设置一下showIndexCoupou，返回首页后会弹窗优惠
      // vk.vuex.set('$app.showIndexCoupou', true)
      console.log('用户点击取消')
    },
		
  }
}
</script>

<style lang="scss" scoped>
	.player-group-nav {
		.recharge-popup-nav {
			::v-deep .u-transition {
				z-index: 10077 !important;
			}
		}
	}

	.balance-modal-nav ::v-deep .u-fade-enter-to {
		z-index: 10078 !important;
	}

	.balance-modal-nav ::v-deep .u-fade-zoom-enter-active {
		z-index: 10078 !important;
	}

	.title-nav {
		padding: 30rpx 20rpx 0 20rpx;
		display: flex;
		align-items: center;
	}

	.video-nave {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		padding: 0 20rpx;

		.video-item {
			width: 31%;
			height: 300rpx;
			position: relative;
			margin-top: 20rpx;
			overflow: hidden;
			border-radius: 20rpx;
		}
	}

	.video-nave::after {
		content: '';
		width: 31%;
	}

	.plaery-ing {
		color: #fff;
		font-size: 24rpx;
		width: 124rpx;
		height: 44rpx;
		line-height: 44rpx;
		text-align: center;
		border-radius: 0 20rpx 0 20rpx;
		background-color: rgba(0, 0, 0, 0.5);
		position: absolute;
		top: 0;
		right: 0;
		z-index: 2;
	}

	.episode-text {
		color: #fff;
		font-size: 24rpx;
		height: 40rpx;
		line-height: 40rpx;
		text-align: center;
		border-radius: 0 0 20rpx 20rpx;
		background-color: rgba(0, 0, 0, 0.5);
		position: absolute;
		bottom: 0;
		width: 100%;
		z-index: 2;
	}

	.lock-nav {
		background-color: rgba(0, 0, 0, 0.6);
		height: 100%;
		width: 100%;
		border-radius: 20rpx 20rpx 0 0;
		position: absolute;
		top: 0;
		z-index: 1;

		.lock-icon {
			position: absolute;
			top: 0;
			bottom: 0;
			left: 0;
			right: 0;
			margin: auto;
			width: 64rpx;
			height: 64rpx;
		}
	}
</style>
